#include <iostream>
using namespace std;
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <cstring>

#define SIZE 4096

void test1(string& filename)
{
    int fd = ::open(filename.c_str(),O_CREAT|O_RDWR,0666);
    if(fd < 0)
    {
        std::cerr<<"open error"<<std::endl;
    }
    //fd默认文件大小是0，不能与mmap进行正确的映射
    ::ftruncate(fd,SIZE);

    char* mmap_addr = (char *)::mmap(nullptr,SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if(mmap_addr == MAP_FAILED)
    {
        perror("mmap");
    }

    for(int i = 0;i<SIZE;i++)
    {
        mmap_addr[i] = 'a'+i%26;
    }

    ::munmap(mmap_addr,SIZE);
    ::close(fd);
}


int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        std::cerr<<"Usage: "<<argv[0]<<" filename"<<std::endl;
        return 1;
    }

    string filename = argv[1];
    test1(filename);

}